package com.zxmr.action;

import java.io.IOException;
import java.util.concurrent.ExecutorService;

import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.QueueingConsumer.Delivery;
import com.zxmr.exception.AuthorizeErrorException;
import com.zxmr.exception.InvalidURLException;
import com.zxmr.navigate.Executor;
import com.zxmr.navigate.RequestDispatch;
import com.zxmr.rabbit.ChannelFactory;

public class QueueWithExchangeReceiver extends QueueReceiver {

	String queue;
	String exchange;
	String routingKey;
	
	public QueueWithExchangeReceiver(ExecutorService es, String queue,String exchange,String routingKey)
	{
		super(es, queue);	
		this.queue = queue;
		this.exchange = queue;
		this.routingKey = queue;
	}
	public QueueWithExchangeReceiver(ExecutorService es,String queue) 
	{	
		this(es,queue,queue,queue);
	}

	@Override
	public void processRequest(Delivery delivery) throws IOException {
		
		// get delivery message and properties
		AMQP.BasicProperties requestProperties = delivery.getProperties();
	    String message = new String(delivery.getBody(),"UTF-8");

	    System.out.println("receive message : "+message);
	    // decode the request message to Request
	    Request request;
		request = JSON.parseObject(message, Request.class);
		request.setRequestProperties(requestProperties);
		
    	final Response response = new Response();
	    response.setRequest(request);

	    // get corresponding executor based on the request URL
		Executor executor;
		try {
			executor = RequestDispatch.getExecutor(request);
		    if(executor!=null)
		    {
		    	response.setResult(ResultCode.SUCCESS);
			    executor.execute(request,response); 
		    }else
		    {
		    	response.setResult(ResultCode.INTERNAL_ERROR);
		    }
		} catch (InvalidURLException e) {
			e.printStackTrace();
			response.setResult(ResultCode.INVALID_URL);
		} catch (AuthorizeErrorException e) {
			e.printStackTrace();
			response.setResult(ResultCode.NOT_AUTHORIZED);
		}catch(Exception e)
		{
			e.printStackTrace();
			response.setResult(ResultCode.INTERNAL_ERROR);
		}
	   // if it need ACK
	   if(request.isNeedResponse())response.send();

	    
	}

	@Override
	public Channel setupChannel() throws IOException {
		Channel channel = ChannelFactory.createChannel();
		
	    channel.queueDeclare(queue, false, false, false, null);
	    channel.exchangeDeclare(exchange, "direct");
	    
	    channel.queueBind(queue, exchange, routingKey);
	    return channel;

	}
}
